import sys
import os
from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QVBoxLayout,
                             QHBoxLayout, QLabel, QLineEdit, QMessageBox,
                             QGroupBox, QFormLayout)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont

# 添加项目根目录到系统路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from database import Database
from iteration5_user_management.login import UserLogin
from student_gui import StudentWindow
from teacher_gui import TeacherWindow
from admin_gui import AdminWindow

# 登录窗口
class LoginWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        
    def initUI(self):
        self.setWindowTitle('宿舍管理系统 - 登录')
        self.setGeometry(300, 300, 400, 200)
        
        # 创建表单布局
        layout = QVBoxLayout()
        
        # 标题
        title_label = QLabel('宿舍管理系统登录')
        title_label.setAlignment(Qt.AlignCenter)
        title_font = QFont()
        title_font.setPointSize(16)
        title_font.setBold(True)
        title_label.setFont(title_font)
        layout.addWidget(title_label)
        
        # 登录表单
        form_layout = QFormLayout()
        
        self.username_input = QLineEdit()
        self.username_input.setPlaceholderText('请输入用户名')
        form_layout.addRow('用户名:', self.username_input)
        
        self.password_input = QLineEdit()
        self.password_input.setPlaceholderText('请输入密码')
        self.password_input.setEchoMode(QLineEdit.Password)
        form_layout.addRow('密码:', self.password_input)
        
        # 添加表单到主布局
        form_group = QGroupBox()
        form_group.setLayout(form_layout)
        layout.addWidget(form_group)
        
        # 登录按钮
        self.login_button = QPushButton('登录')
        self.login_button.clicked.connect(self.login)
        layout.addWidget(self.login_button)
        
        self.setLayout(layout)
    
    def login(self):
        username = self.username_input.text()
        password = self.password_input.text()
        
        if not username or not password:
            QMessageBox.warning(self, '警告', '用户名和密码不能为空')
            return
        
        user_login = UserLogin()
        success, user = user_login.login(username, password)
        
        if success and user:
            # 根据用户角色打开相应的窗口
            if isinstance(user, dict):
                role = user.get('role')
            elif isinstance(user, tuple) and len(user) > 2:
                role = user[2]
            else:
                role = 'unknown'
            
            # 根据角色打开不同的窗口
            if role == 'admin':
                self.admin_window = AdminWindow(user)
                self.admin_window.show()
            elif role == 'teacher':
                self.teacher_window = TeacherWindow(user)
                self.teacher_window.show()
            elif role == 'student':
                self.student_window = StudentWindow(user)
                self.student_window.show()
            else:
                QMessageBox.warning(self, '警告', '未知的用户角色')
                return
                
            # 关闭登录窗口
            self.close()
        else:
            QMessageBox.critical(self, '错误', '登录失败: 用户名或密码错误')

def main():
    # 初始化数据库
    db = Database()
    db.init_db()
    
    # 检查是否有管理员用户，如果没有则创建默认管理员
    db.connect()
    db.cursor.execute("SELECT COUNT(*) FROM user WHERE role = 'admin'")
    admin_count = db.cursor.fetchone()[0]
    db.close()
    
    if admin_count == 0:
        from iteration5_user_management.create_user import UserCreator
        creator = UserCreator()
        creator.create_user('admin', 'admin123', 'admin', '系统管理员', None)
        print("已创建默认管理员账户 (用户名: admin, 密码: admin123)")
        
        # 创建默认老师账户
        creator.create_user('teacher', 'teacher123', 'teacher', '测试老师', None)
        print("已创建默认老师账户 (用户名: teacher, 密码: teacher123)")
        
        # 创建默认学生账户
        creator.create_user('student', 'student123', 'student', '测试学生', None)
        print("已创建默认学生账户 (用户名: student, 密码: student123)")
    
    # 创建应用程序
    app = QApplication(sys.argv)
    
    # 创建登录窗口
    login_window = LoginWindow()
    login_window.show()
    
    # 运行应用程序
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()